package com.rytong.tools.ui;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils.TruncateAt;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import com.rytong.tools.utils.LPToastUtil;
import com.rytong.tools.utils.Utils;
import com.rytong.tools.utils.InputMethodUtil.onCloseImmListener;

public class LPSelect extends Component {
    // XML & XHTML property "multiple".
    private static final String ATTRIBUTE_MULTIPLE = "multiple";

    // 改变量保证界面上始终只有一个由下拉框控件触发的弹出框出现
    public volatile static boolean ISPOPING;

    private static final int SELECT_FONT_SIZE_DEFAULT = 15;
    // Margins used when rendering text.
    // protected static final int Y_MARGIN = 1;
    //
    // static final int textColor_ = ConfigManager.COLOR_DKGRAY;
    //
    // private static final int textSize_ = ConfigManager.SIZE_MEDIUM;
    //
    private static int MARGIN_ARROW = 5;

    /* pop views. */
    static Dialog ad_;
    private static SelectScrollView sc_;

    // 定义弹出界面的最大宽度
    private static final int maxWidth_ = 250;
    private static final int ITEM_MARGIN = 2;
    // 字符留白
    private final int textBlank_ = 0;

    /** Variables for item drop down menu */
    /** In this vector contains all items text of this dropdownMenu */
    private ArrayList<LPSelectOption> dropDownOptions_;
    //复制当前Select的options
    private ArrayList<Component> childArrayListCopy_;
    /** In this vector contains all options */
    private ArrayList<LPSelectOption> allOptions_;
    private String currentGroup_;

    // String textAlign_;
    private int fontSize_;
    private int indStar_ = 0; // the index start to paint.
    private int currentMenu_;
    // 该背景色为弹出选择框以后的那个弹出框背景色
    // static int bgColor_ = ConfigManager.COLOR_DKGRAY;

    private int ddmTotalHeight_;
    private Bitmap arrImg_;

    private Bitmap[] backgroundBitmap_;

    private  Bitmap arrowImg_;

    /** 设置下拉框里各条目的字体颜色与大小 */
    int textColor_ = 0xff000000;
    int textSize_ = 18;

    /** 下拉框所点击项 */
    private int index1;
    
    /** 初始化时候的背景色*/
    public String oldBG_ = null;
    
    /**
     * View shown on the screen before popping out.
     */
    public class MyLPSelect extends TextView implements CompositedComponent {

        public MyLPSelect(Context context) {
            super(context);
            setFocusable(true);
            setFocusableInTouchMode(true);
            setGravity(Gravity.CENTER_VERTICAL);
            setSingleLine(true);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            final int height = getHeight();
            final int width = getWidth();
            Paint paint = getPaint();
            // draw arrow
            super.onDraw(canvas);
            // 画字体
            // canvas.drawText(getContentText(), 0, ((int) (height + paint_.getTextSize())) >> 1, paint_);
            // 画提示信息
            if (getPropertyByName("hold") != null) {
                canvas.drawText((String) getPropertyByName("hold"), 0, ((int) (height + paint.getTextSize())) >> 1,
                        paint);
            }
            
            if(LPToastUtil.getInstance().isBranchBank && !LPToastUtil.getInstance().isHasStyle){
                if (arrowImg_ != null) {
                    canvas.drawBitmap(arrowImg_, width - arrowImg_.getWidth(), (height - arrowImg_.getHeight()) >> 1, paint);
                }
            }
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            int action = event.getAction();
            boolean isAction = false;
            switch (action) {
            case MotionEvent.ACTION_DOWN:
            	// 按下tr时候变色。
            	trDownColor(tr_, llvSV_);
            	// 向滚动视图中登记这个按钮，以便在滚动视图抢夺焦点的时候还原颜色。
            	if(Utils.sc_ != null){
            		Utils.sc_.focusObj_ = this.composited();
            	}
            	if(hs_ != null){
            		hs_.focusObj_ = this.composited();
            	}
            	if(vs_ != null){
            		vs_.focusObj_ = this.composited();
            	}
            	// 按下的时候改变select的背景图。
            	realView_.setBackgroundColor(Color.parseColor(Component.fixedPX(Utils.TR_CHANGE_BG_)));
                xDown_ = event.getX();
                yDown_ = event.getY();
                setPressed(true);
                invalidate();
                isAction = true;
                break;
            case MotionEvent.ACTION_MOVE:
            	// 移动tr恢复颜色。
            	int offset = (int) Math.abs(yDown_ - event.getY());
            	if (offset > offset_) {
            		trMoveColor(tr_, llvSV_);
            		// 移动的时候恢复select的背景图。
            		if(oldBG_ == null || "".equals(oldBG_)){
            			realView_.setBackgroundColor(0);
            		} else {
            			realView_.setBackgroundColor(Color.parseColor(Component.fixedPX(oldBG_)));
            		}
            	}
                moveY(yDown_, event.getY());
                break;
            case MotionEvent.ACTION_UP:
            	recoveColor();
                requestFocus();
                invalidate();
                // 预防控件出现连击效果
                long currentTime = System.currentTimeMillis();
                long timedifference = currentTime - LASTCLICKTIME;
                if (timedifference < 0) {
                    LASTCLICKTIME = currentTime;
                } else if (timedifference < jetLag_) {
                    LASTCLICKTIME = currentTime;
                    return false;
                } else {
                    LASTCLICKTIME = currentTime;
                }
                if (!LPSelect.ISPOPING) {
                    String attrAccessory = accessory();
                    LPSelect select = (LPSelect) composited();
                    if ((null != attrAccessory) && (!attrAccessory.equals(""))) {
                    } else {
                        xUp_ = (int) event.getX();
                        yUp_ = (int) event.getY();
                        // 如果x或者y方向移动小于VALUE_个像素才判断为点击弹起，如果大于VALUE_个像素则判断为移动，不执行弹起效果
                        if (Math.abs(xUp_ - xDown_) > offset_ || Math.abs(yUp_ - yDown_) > offset_) {
                            return false;
                        }
                        LPSelect.ISPOPING = true;
                        isAction = TouchWidthNormal((Activity) realView_.getContext(), select);
                    }
                }
                break;
            default:
                isAction = super.onTouchEvent(event);
            }

            return isAction;
        }

        /**
         * 按下的时候抬起
         */
        private void recoveColor(){
        	// 抬起tr恢复颜色。
        	trUpColor(tr_, llvSV_);
        	// 向滚动视图中登记这个按钮，以便在滚动视图抢夺焦点的时候还原颜色。
        	if(Utils.sc_ != null){
        		Utils.sc_.focusObj_ = null;
        	}
        	if(hs_ != null){
        		hs_.focusObj_ = null;
        	}
        	if(vs_ != null){
        		vs_.focusObj_ = null;
        	}
        	// 抬起的时候恢复select的背景图。
        	if(oldBG_ == null || "".equals(oldBG_)){
    			realView_.setBackgroundColor(0);
    		} else {
    			realView_.setBackgroundColor(Color.parseColor(Component.fixedPX(oldBG_)));
    		}
        	
        	//将其父控件td背景设置为透明
        	if(null != LPSelect.this.getParent()){
        		(LPSelect.this.getParent().realView_).setBackgroundColor(0);
        		LPSelect.this.getParent().realView_.invalidate();
        	}
        }
        
        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            int action = event.getAction();
            // 上下左右响应该控件的原始效果
            if ((keyCode == KeyEvent.KEYCODE_DPAD_UP) || (keyCode == KeyEvent.KEYCODE_DPAD_DOWN)
                    || (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) || (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)
                    || (keyCode == KeyEvent.KEYCODE_BACK)) {
                return super.onKeyDown(keyCode, event);
            }
            String attrAccessory = accessory();
            if ((null != attrAccessory) && (!attrAccessory.equals(""))) {
                switch (action) {
                case KeyEvent.ACTION_UP:
                    if (!LPSelect.ISPOPING) {
                        LPSelect.ISPOPING = true;
                    }
                    break;
                default:
                    return super.onKeyDown(keyCode, event);
                }
            } else {
                switch (action) {
                case MotionEvent.ACTION_DOWN:
                    if (!LPSelect.ISPOPING) {
                        // LPSelect.ISRUNNING = true;
                        TouchWidthNormal((Activity) realView_.getContext(), (LPSelect) composited());
                    }
                    break;
                default:
                    return super.onKeyDown(keyCode, event);
                }
            }
            return true;
        }

        @Override
        public Component composited() {
            return LPSelect.this;
        }

        /**
         * @return
         */
        private int textColor() {
            CssStyle cs = cssStyle();
            int textColor = cs != null ? fgColor() : SELECT_DEFAULT_TEXT_COLOR;
            return textColor;
        }
    }

    /**
     * Scroll view to contain all the views in the pop view.
     * 
     * @author Chris
     * 
     */
    private static final class SelectScrollView extends ScrollView {

        private final int[] shadeColors_ = new int[] { SELECT_DEFAULT_POP_BACKGROUD_COLOR, Color.WHITE };
        private final Paint paint_;
        private Shader shader_;
        private final LinearLayout ll_;

        private SelectScrollView(Context context) {
            super(context);
            ll_ = new LinearLayout(context);
            ll_.setOrientation(LinearLayout.VERTICAL);

            ViewGroup.LayoutParams lop = new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            ll_.setLayoutParams(lop);

            super.addView(ll_);

            paint_ = new Paint();
            paint_.setStyle(Style.FILL);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            if (shader_ == null) {
                shader_ = new LinearGradient(0, 0, 0, getHeight(), shadeColors_, null, Shader.TileMode.CLAMP);
                paint_.setShader(shader_);
            }
            canvas.drawRect(0, 0, getWidth(), getHeight(), paint_);
            super.onDraw(canvas);
        }

        @Override
        public void addView(View child) {
            ll_.addView(child);
        }

        /**
         * 
         */
        private void cleanContents() {
            if (ll_ == null) {
                return;
            }
            ll_.removeAllViews();
        }
    }

    /**
     * @return
     */
    public LPSelectOption getCurrentOption() {
        LPSelectOption currentOption = null;
        try {
            currentOption = (LPSelectOption) dropDownOptions_.get(currentMenu_);
        } catch (Exception ex) {
            Utils.printException(ex);
        }
        return currentOption;
    }

    /**
     * @param o
     */
    void setDropdownMenuText(LPSelectOption o) {
        if (o == null) {
            return;
        }
        o.lpselect_ = this;
        String ref = o.ref_;
        if (ref == null || currentGroup_ == null || ref.equals(currentGroup_)) {
            currentGroup_ = ref;
            addDropdownOption(o);
        }
    }

    /**
     * 该方法主要用于指定控件的大小\显示颜色\样式等,如果服务端没有给定输出样式大小,则要自行计算一个合适的大小应用于该控件 Mould this component with its shape, color, size and
     * so on.
     * 
     * @return
     * @throws Exception
     *             TODO
     */

    public void mouldH() throws Exception {
        super.mouldH();
        childArrayListCopy_ = childrenList_;
        // 设置默认选项
        setSelectedOption();
        if (null != cssStyle_) {
            mouldCssStyle();
            // 记录后台给的背景色。
            oldBG_ = cssStyle_.getProperty(CssStyle.BACKGROUNDCOLOR);
        }
        LayoutParams viewLayout = null;
        viewLayout = (LayoutParams) getLayoutParams();
        /**
         * 计算select的宽度，如果后台指定了宽度，就使用后台给定的值，
         * 如果不指定，那么就取option中内容最多的那段文字的宽度，
         */
        if(cssStyle_ != null && cssStyle_.getProperty(CssStyle.WIDTH) != null
        		&& !"".equalsIgnoreCase(cssStyle_.getProperty(CssStyle.WIDTH))){
        	// 这里后台给定了宽度，在super.muold()中宽度已经计算出来了，此处不进行宽度的计算。
        } else { // 计算出最长option的长度。
        	int maxLength = 0;
            if (childrenList_ != null && childrenList_.size() > 0) {
                for (int i = 0; i < childrenList_.size(); i++) {
                	LPSelectOption option = (LPSelectOption) childrenList_.get(i);
                	maxLength = (int) Math.max(maxLength, getPaint().measureText(option.getContentText()));
                }
            }
            if(maxLength > 0){ // 如果算出来了最长宽度，那么就使用这个值，否则将采用默认的widget中规定的值。
            	viewLayout.width = maxLength;
            }
            
            //如果是分行特色，select控件加一定的像素，否则画箭头的时候会覆盖文字
            if(LPToastUtil.getInstance().isBranchBank){
            	viewLayout.width = viewLayout.width + Utils.getScaledValueX(20);            	
            }
        }
        // 为了能够完整显示gjpy等小写字母，特别加上一段高度。
        viewLayout.height = height_ + Utils.getScaledValueY(3);
        setLayoutParams(viewLayout);
    }

    /**
     * 更新样式赋值�?�由于�?�lua中会有更新样式的操作，但是不涉及控件大小的改变，所以将此部分单独出来�?
     */
    public void mouldCssStyle() {
        try {
            // TODO Auto-generated method stub
            super.mouldCssStyle();
            MyLPSelect mlpl = (MyLPSelect) realView_;
            if (null != unFocusImg_)
                mlpl.setBackgroundDrawable(new BitmapDrawable(unFocusImg_));
            
            if (cssStyle_ != null) {
                String temp = cssStyle_.getProperty(CssStyle.BACKGROUNDCOLOR);
                if (null != temp && !temp.equals("")) {
                    int bgColor = Color.parseColor(temp);
                    realView_.setBackgroundColor(bgColor);
                }
            }
           
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
    }

    /**
     * Append the option into the pop list.
     * 
     * @param o
     */
    void addDropdownOption(LPSelectOption o) {
        dropDownOptions_.add(o);
    }

    /**
     * @param group
     */
    void resetDropdownMenuText(String group) {
        if (allOptions_ == null || group == null || group.equals(currentGroup_)) {
            // There is NO option, or no group has been referred to, or the
            // group is just the current group.
            return;
        }
        currentGroup_ = group;
        setContentText(null, null);
        cleanOptionsInPopView();
        // ddmMaxWidth_ = ddmTotalHeight_ = ddmXStar_ = ddmYStar_ = 0;
        ddmTotalHeight_ = 0;
        setCurrentMenu(0);
        // settleRelationAction(); //modify 2009-04-22
        // bv_.reCalculateTotalWH(); // have do it in
        // dropdownMenuClickItem().
        width_ = SCREENWIDTH;
        height_ = 7;
        for (int i = 0; i < allOptions_.size(); i++) {
            LPSelectOption o = allOptions_.get(i);
            if (o.ref_ == null || !group.equals(o.ref_)) {
                // means the ref of the option is NOT as same as the group.
                continue;
            }
            addDropdownOption(o);
            if (getContentText() == null) {
                setContentText(o.label(), (String) o.getPropertyByName("value")); // defaultText
            }
        }
    }

    /**
     * @param optn
     */
    private void setRelative(LPSelectOption optn) {
        try {
            setRelaEnable(optn.relaEnable_);
            setRelaDisable(optn.relaDisable_);
            setRelaVisible(optn.relaVisible_);
            setRelaInvisible(optn.relaInvisible_);
        } catch (Exception ex) {
            Utils.printException(ex);
        }
    }

    @Override
    public void cleanText() {
        // repuplate the other when it is changed
        if (realView_ != null && realView_.isShown()) {
            LPSelectOption o = (LPSelectOption) dropDownOptions_.get(currentMenu_);
            setContentText(o.label(), (String) o.getPropertyByName("value"));
        }
    }

    /**
     * @param group
     * @return
     */
    private boolean isRefWithGroup(String group) {
        if (allOptions_ == null && group == null) {
            return false;
        }
        for (int i = allOptions_.size() - 1; i >= 0; i--) {
            LPSelectOption o = (LPSelectOption) allOptions_.get(i);
            if (group.equals(o.ref_)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param parent
     * @param select
     */
    public boolean TouchWidthNormal(final Activity parent, final LPSelect select) {
        int size = childrenList_.size();
        Component[] views = new Component[size];
        for (int i = 0; i < size; i++) {
            views[i] = (Component) childrenList_.get(i);
        }
        
        /*showPopView(parent, views);
         //使用系统样式的下拉款
        showAndroidPopView(parent, views, select);*/
        
        //自定义WheelViewSelect
        final Component[] temp = views;
		Utils.immUtils.setOnCloseImmListener(parent,new onCloseImmListener() {
			@Override
			public void closeSuccess() {
				showAndroidWheel(parent, temp, select);
			}
		});
        return true;
    }

    /**
     * 自定义的滚轮选择View
     * @param context
     * @param views
     * @param currentSelect
     */
    /**
     * @param context
     * @param views
     * @param currentSelect
     */
    public void showAndroidWheel(Context context, final Component[] views, final LPSelect currentSelect){
        int size = views.length;
        final String[] viewItems = new String[size];
        for (int i = 0; i < size; i++) {
            viewItems[i] = (String) views[i].property_.get("text");
        }
        
    	View view = LayoutInflater.from(context).inflate(Utils.getResourcesId(context, "layout_select_popup", "layout"), null);
    	LinearLayout parent = (LinearLayout)view.findViewById(Utils.getResourcesId(context, "wheelParent", "id"));
    	
    	final WheelView wheel = new WheelView((Activity)context);
    	wheel.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
    	wheel.setPadding(5, 5, 5, 5);
    	wheel.setAdapter(new ArrayWheelAdapter<String>(viewItems));
    	parent.addView(wheel);
    	
    	if(currentMenu_ >=0 && currentMenu_ <= childrenList_.size()){
    		wheel.setCurrentItem(currentMenu_);
    	}
    	
    	int styleId = Utils.getResourcesId(context, "popupAnimation", "style");
		final Dialog mCertDialog = new Dialog(context, styleId);
		mCertDialog.setContentView(view);
		mCertDialog.setCancelable(true);
		
		Window mWindow = mCertDialog.getWindow();
		mWindow.setWindowAnimations(styleId);
		mWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		mWindow.setGravity(Gravity.BOTTOM | Gravity.FILL_HORIZONTAL);
		mWindow.setLayout(ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
    	
		Button confirm = (Button)view.findViewById(Utils.getResourcesId(context, "confirm", "id"));
		Button cancel = (Button)view.findViewById(Utils.getResourcesId(context, "cancel", "id"));
		
		// 确定按钮
		confirm.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int index = wheel.getCurrentItem();
				if(views != null && views.length > 0){
					currentSelect.setCurrentMenu(index);
					LPSelectOption tempOption = (LPSelectOption) views[index];
					currentSelect.setContentText(viewItems[index], (String) tempOption.getPropertyByName("value"));
					attrValue_=(String) tempOption.getPropertyByName("value");
					currentSelect.invalidate();
					currentMenu_ = index;
					LPSelect.ISPOPING = false;
					//控件关联
					resetOtherSelectOptions(currentSelect,tempOption);
					tempOption.onClick((String) tempOption.property_.get("onclick"));
				}
                mCertDialog.dismiss();
			}
		});
		
		cancel.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				LPSelect.ISPOPING = false;
				mCertDialog.dismiss();
			}
		});
		
		if(null != mCertDialog && !mCertDialog.isShowing()){
			mCertDialog.show();
			mCertDialog.setOnDismissListener(new OnDismissListener() {
				
				@Override
				public void onDismiss(DialogInterface dialog) {
					// TODO Auto-generated method stub
					LPSelect.ISPOPING = false;
				}
			});
		}
    }
    
    /**
     * 控件联动方法
     * @param lpSelect
     * @param option
     */
    public void setVisibleInvisible(LPSelect lpSelect,LPSelectOption option){
    	if(null != option && LPToastUtil.getInstance().isBranchBank){
    		String invisible = option.getPropertyByName("invisible");
    		String visible = option.getPropertyByName("visible");
    		Utils.setCompontentsLinked(visible, invisible);
    	}
    }
    
    /**
     * 控件联动，当选择其中一个时，过滤并更新与之关联的select控件的option元素
     * @param name
     */
    public void resetOtherSelectOptions(LPSelect lpSelect,LPSelectOption option){
    	//控件隐藏联动
    	setVisibleInvisible(lpSelect,option);

    	String associate = lpSelect.getPropertyByName("associate");
    	if(null == associate || "".equalsIgnoreCase(associate) || null == option){
    		return;
    	}
    	
    	String[] names = associate.split(",");
    	for(int i = 0;i < names.length;i++){
    		Component comp = getElementByName(names[i]);
    		if(null != comp && comp instanceof LPSelect){
    			LPSelect lpsl = (LPSelect)comp;
    			resetOptions(lpsl,option);
    			setSelectedOption(lpsl);
    		}    		
    	}
    }
    
    /**
     * 通过选择的Option 重置其他的Select控件的Options
     * @param option
     */
    private void resetOptions(LPSelect lpSelect,LPSelectOption option) {
		// TODO Auto-generated method stub
		String searchKey = option.getPropertyByName("key");
		if(null != searchKey && !"".equalsIgnoreCase(searchKey)){
			int size = lpSelect.childArrayListCopy_.size();
			ArrayList<Component> temp = new ArrayList<Component>();
			for(int i = 0;i < size;i++){
				Component o = lpSelect.childArrayListCopy_.get(i);
				if(o instanceof LPSelectOption){
					String key = (String)o.getPropertyByName("searchkey");
					if(key.equalsIgnoreCase(searchKey)){
						temp.add(o);
					}
				}
			}
			
			lpSelect.childrenList_ = temp;
		}
	}
    
    /**
     * 设置默认选项
     */
    public void setSelectedOption(LPSelect lpsl) {
        if (lpsl.childrenList_ == null || lpsl.childrenList_.size() <=0)
            return;
        Component comp = null;
        int size = lpsl.childrenList_.size();
        LPSelectOption selectOption = null;
        for (int i = 0; i < size; i++) {
            comp = lpsl.childrenList_.get(i);
            if (comp instanceof LPSelectOption) {
                LPSelectOption option = (LPSelectOption) comp;
                if (option.isSelected_) { 
                	selectOption = option;
                    break;
                }
            }
        }
        
        if(null == selectOption){
        	selectOption = (LPSelectOption) lpsl.childrenList_.get(0);
        }else{
        	return ;
        }
    	lpsl.setContentText(selectOption.getContentText(), selectOption.getPropertyByName("value").toString());
        // 将select的值默认赋为第一个被选中的option的value。
    	lpsl.attrValue_ = selectOption.getPropertyByName("value");
    	lpsl.currentMenu_ = 0;
    	lpsl.invalidate();
    	if(null != lpsl.getPropertyByName("associate") && !"".equalsIgnoreCase(lpsl.getPropertyByName("associate"))){
    		resetOtherSelectOptions(lpsl,selectOption);
    	}
    }

	/**
     * 通过名字得到控件元素
     * @param name
     */
    private Component getElementByName(String name){
    	Component compontent = null;
        int size = Component.VWIDGETARRAY.size();
        for (int i = 0; i < size; i++) {
            Object o = Component.VWIDGETARRAY.get(i);
            if (o instanceof Component) {
            	Component view = (Component) o;
                String tagName = (String) view.property_.get("name");
                if (null != tagName) {
                    if (name.equals(tagName)){
                    	compontent = view;
                    }
                }
            }
        }
        
        return compontent;
    }
    
    public void showAndroidPopView(Context context, Component[] views, LPSelect select) {
        int size = views.length;
        String[] viewItems = new String[size];
        for (int i = 0; i < size; i++) {
            viewItems[i] = (String) views[i].property_.get("text");
        }

        // 获取下拉框视图
        LayoutInflater factory = LayoutInflater.from(context);
        int listview_layout = Utils.getResourcesId(getContext(), "listview", "layout");
        View view = factory.inflate(listview_layout, null);
        int listView01_id = Utils.getResourcesId(getContext(), "ListView01", "id");
        ListView listview = (ListView) view.findViewById(listView01_id);
        listview.setBackgroundColor(Color.WHITE);
        List<String> arrayList = new ArrayList<String>();
        arrayList = Arrays.asList(viewItems);

        // 设置适配器
        DialogAdapter dialogAdapter = new DialogAdapter(context, arrayList);
        listview.setAdapter(dialogAdapter);

        // 设置点击事件
        ItemClickAcion itemClickAcion = new ItemClickAcion();
        listview.setOnItemClickListener(itemClickAcion);

        // 设置选中事件
        ItemSelectAction itemSelectAction = new ItemSelectAction();
        listview.setOnItemSelectedListener(itemSelectAction);

        // 创建button事件
        ButtonAction buttonAction = new ButtonAction(currentMenu_, select, viewItems);
        buttonAction.setIndex(currentMenu_);
        AlertDialog alertDialog = new AlertDialog.Builder(context).setTitle("请选择").setView(listview)
                .setPositiveButton("确定", buttonAction).setNegativeButton("取消", buttonAction).create();
        alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                if (LPSelect.ISPOPING) {
                    LPSelect.ISPOPING = false;
                }
            }
        });
        alertDialog.show();
    }

    private class DialogAdapter extends BaseAdapter {
        Context context;
        List<String> list;

        public DialogAdapter(Context context, List<String> list) {
            this.context = context;
            this.list = list;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            int item_layout = Utils.getResourcesId(getContext(), "item", "layout");
            LinearLayout linearLayout = (LinearLayout) ((Activity) context).getLayoutInflater().inflate(item_layout,
                    null);
            int checkedTextView_id = Utils.getResourcesId(getContext(), "checkedTextView", "id");
            CheckedTextView checkedTextView = (CheckedTextView) linearLayout.findViewById(checkedTextView_id);
            checkedTextView.setText(list.get(position));
            // 设置字体大小及颜色
            checkedTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize_);
            checkedTextView.setTextColor(textColor_);
            // 设置选中项
            checkedTextView.setChecked(false);
            if (position == currentMenu_) {
                checkedTextView.setChecked(true);
            }
            return linearLayout;
        }

    }

    private class ItemClickAcion implements OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            // TODO Auto-generated method stub
            // 把所有的单选全部设为非选中
            int checkedTextView = Utils.getResourcesId(getContext(), "checkedTextView", "id");
            for (int i = 0; i < arg0.getCount(); i++) {
                View v = arg0.getChildAt(i);
                if (null != v) {
                    CheckedTextView checkText = (CheckedTextView) v.findViewById(checkedTextView);
                    checkText.setChecked(false);
                }
            }
            // 获得点击项的CheckedTextView，并设为选中
            CheckedTextView check = (CheckedTextView) arg1.findViewById(checkedTextView);
            check.setChecked(true);
            index1 = arg2;
        }

    }

    private class ItemSelectAction implements OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            int checkedTextView = Utils.getResourcesId(getContext(), "checkedTextView", "id");
            CheckedTextView check = (CheckedTextView) view.findViewById(checkedTextView);
            check.setChecked(true);
            index1 = position;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }

    }

    private class ButtonAction implements DialogInterface.OnClickListener {

        LPSelect currentSelect;
        String[] items;

        public ButtonAction(int index, LPSelect select, String[] viewItems) {
            index1 = index;
            currentSelect = select;
            items = viewItems;
        }

        public void setIndex(int index) {
            index1 = index;
        }

        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
            case DialogInterface.BUTTON_POSITIVE:
                if (index1 < 0 || index1 > items.length - 1)
                    return;
                // 确定按钮
                currentSelect.setCurrentMenu(index1);
                LPSelectOption tempOption = (LPSelectOption) currentSelect.childrenList_.get(index1);
                currentSelect.setContentText(items[index1], (String) tempOption.getPropertyByName("value"));
                attrValue_=(String) tempOption.getPropertyByName("value");
                currentSelect.invalidate();
                currentMenu_ = index1;
                LPSelect.ISPOPING = false;

                tempOption.onClick((String) tempOption.property_.get("onclick"));
                
                break;
            case DialogInterface.BUTTON_NEGATIVE:
                LPSelect.ISPOPING = false;
                break;
            default:
                break;
            }
        }

    }

    /**
     * After invoking it, there are no options in the pop list.
     */
    public void cleanOptionsInPopView() {
        dropDownOptions_.removeAll(dropDownOptions_);
    }

    /**
     * @param buttonWidth
     * @param buttonHeight
     */
    private Bitmap[] createBackground(int buttonWidth, Bitmap[] backgroundBitmap) {
        int size = backgroundBitmap.length;
        for (int i = 0; i < size; i++) {
            try {
                backgroundBitmap[i] = LPButton.makeButton(backgroundBitmap[i], buttonWidth);
            } catch (Exception e) {
                Utils.printException(e);
            }
        }
        return backgroundBitmap;
    }

    /**
     * @param context
     */
    private void createImg(Context context) throws Exception {
        /** Create button images */
        // Create arrow image.
        if (arrowImg_ == null) {
            arrowImg_ = ImageRepository.getImageFromAssetFile(context, "select_arr.png");
        }
    }

    /**
     * @return
     */
    public String currentLabel() {
        if (dropDownOptions_ == null) {
            return null;
        }
        LPSelectOption o = dropDownOptions_.get(currentMenu_);
        if (o == null) {
            return null;
        }
        return o.label();
    }

    /**
     * @return
     */
    public String currentValue() {
        return value(currentMenu_);
    }

    /**
     * @param index
     * @return
     */
    public String value(int index) {
        if (dropDownOptions_ == null) {
            return null;
        }
        LPSelectOption o = dropDownOptions_.get(index);
        if (o == null) {
            return null;
        }
        return (String) o.property_.get("value");
    }

    /**
     * @return
     */
    public boolean isEmpty() {
        if (dropDownOptions_ == null) {
            return true;
        }
        if (dropDownOptions_.size() < 1) {
            return true;
        }
        return false;
    }

    /**
     * @return
     */
    public int size() {
        if (allOptions_ == null) {
            return 0;
        }
        return allOptions_.size();
    }

    /*
     * ************************************************************************
     * Set and Get methods. ************************************************************************
     */
    /**
     * @return the currentMenu_
     */
    public int currentMenu() {
        return currentMenu_;
    }

    /**
     * Set the index which option is selected.
     * 
     * @param index
     */
    public void setCurrentMenu(int index) {
        int size = 0;
        if (dropDownOptions_ != null) {
            size = dropDownOptions_.size();
        } else {
            return;
        }
        if (index >= 0 && index < size) {
            currentMenu_ = index;
        }
    }

    @Override
    public void initRealView(Activity activity, String value) {
        // TODO Auto-generated method stub
        realView_ = new MyLPSelect(activity);
        childrenList_ = new ArrayList<Component>(2);
        try {
            createImg(activity);
        } catch (Exception e) {
            Utils.printException(e);
        }
    }

    /**
     * 
     */
    private void setSelectView(LPSelectOption lpso) {
        try {
            setContentText(lpso.label(), (String) lpso.getPropertyByName("value"));
            ad_.dismiss();
            LPSelect.ISPOPING = false;
        } catch (Exception e) {
            Utils.printException(e);
        }
    }

    public void setContentText(String text, String value) {
        MyLPSelect mlps = (MyLPSelect) realView_;
        setPropertyByName("value", value == null ? "" : value);
        setPropertyByName("text", text == null ? "" : text);
        
		//内容长度大于控件宽度以省略号结束
        mlps.setEllipsize(TruncateAt.END);
        mlps.setText(text);
        
    	//将其父控件td背景设置为透明
    	if(null != LPSelect.this.getParent()){
    		(LPSelect.this.getParent().realView_).setBackgroundColor(0);
    		LPSelect.this.getParent().realView_.invalidate();
    	}
    }

    private static void showPopView(Context context, Component[] views) {
        // 赋空ad_，否则在弹出界面按BACK键再点击下拉框会出现弹出框无内容情况
        if (ad_ != null) {
            ViewGroup vg = (ViewGroup) sc_.getParent();
            // 由于引用的ll_管理器唯一，如果此处不将管理器清空，Alert又重新设置该管理器的时候会报管理器已设置（添加）异常
            if (null != vg) {
                vg.removeAllViews();
            }
            ad_ = null;
        }
        ad_ = new Dialog(context);
        // views_ = views;

        // 初始化垂直滚动域
        if (null == sc_) {
            sc_ = new SelectScrollView(context);
        } else {
            sc_.cleanContents();
        }

        int size = (views != null) ? views.length : 0;
        Component view = null;
        for (int i = 0; i < size; i++) {
            view = views[i];
            // 将非输入控件添加至垂直管理器，用于添加至滑动域用
            sc_.addView(view.realView_);
        }

        // 将非包含输入控件的管理器添加至滑动域，方便滑动查看浏览
        ad_.setContentView(sc_);
        ad_.show();
    }

    /**
     * 设置默认选项
     */
    public void setSelectedOption() {
        if (childrenList_ == null)
            return;
        Component comp = null;
        int size = childrenList_.size();
        for (int i = 0; i < size; i++) {
            comp = childrenList_.get(i);
            if (comp instanceof LPSelectOption) {
                LPSelectOption option = (LPSelectOption) comp;
                if (option.isSelected_) { // 如果发现了带有selected="selected"属性的option，就进行赋值操作。
                	// select控件默认显示的文字。
                    setContentText(option.getContentText(), option.getPropertyByName("value").toString());
                    // 将select的值默认赋为第一个被选中的option的value。
                    attrValue_ = option.getPropertyByName("value");
                    currentMenu_ = i;
                    return;
                }
                String text = getContentText();
                if (null == text || text.equals("")) { // 默认select的显示文字和value都是第一个option的文字和value。
                	// 显示的默认文字。
                    setContentText(option.getContentText(), option.getPropertyByName("value").toString());
                    // 设置默认值。
                    attrValue_ = option.getPropertyByName("value");
                    currentMenu_ = i;
                }
            }
        }
    }

	public void setOnClick(LPSelectOption option) {
		// TODO Auto-generated method stub
		if(null != option){
			option.onClick((String) option.property_.get("onclick"));
		}
	}
    
    @Override
    public void releaseResource(Component component) {
    	// TODO Auto-generated method stub
    	super.releaseResource(component);
    	Utils.releaseObject(arrImg_);
    	Utils.releaseObject(arrowImg_);
    	
    	if(null != backgroundBitmap_ && backgroundBitmap_.length > 0){
    		for(int i = 0;i < backgroundBitmap_.length;i++){
    			Utils.releaseObject(backgroundBitmap_[i]);
    		}
    	}
    	
    	if(null != childArrayListCopy_){
    		childArrayListCopy_.clear();
    		childArrayListCopy_ = null;
    	}
    	
    	if(null != dropDownOptions_){
    		dropDownOptions_.clear();
    		dropDownOptions_ = null;
    	}
    	
    	if(null != allOptions_){
    		allOptions_.clear();
    		allOptions_ = null;
    	}
    }
}
